package com.example.java_second_hand_market;

import javafx.beans.property.SimpleStringProperty;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.fxml.FXML;
import javafx.geometry.Pos;
import javafx.scene.Scene;
import javafx.scene.control.*;
import javafx.scene.control.cell.PropertyValueFactory;
import javafx.scene.layout.BorderPane;
import javafx.scene.layout.HBox;
import javafx.scene.layout.VBox;
import javafx.stage.Stage;

import java.sql.*;
import java.util.List;


public class SearchDialog extends Stage {
    BorderPane bp;
    String DBUrl=ParameterDB.ParaDBUserUrl;
    String DBUser="root", DBPassword="123456";
    @FXML
    Label searchlb = new Label("搜索");
    @FXML
    TextField searchfld = new TextField();
    @FXML
    Button search =new Button("搜索");
    private final int ROWS_PER_PAGE = 10;
    @FXML
    private TableView<Item> tableView = new TableView<>();
    @FXML
    private Pagination pagination;
    private ObservableList<Item> data=FXCollections.observableArrayList();
    @FXML
    Button submit = new Button("详情");

    Buyer by;
    Item it;
    String sw;
    public SearchDialog(Buyer by,int width,int height){
        this.by=by;
        pagination =new Pagination(1);
        setupTableView();
        VBox vbox = new VBox(tableView, pagination);
        HBox hb1=new HBox(searchlb,searchfld,search);
        hb1.setAlignment(Pos.CENTER);
        HBox hb2=new HBox(submit);
        hb2.setAlignment(Pos.CENTER);
        bp= new BorderPane();
        bp.setCenter(vbox);
        bp.setTop(hb1);
        bp.setBottom(hb2);
        Scene scene=new Scene(bp);
        this.setScene(scene);
        search.setOnAction(new EventHandler<ActionEvent>() {
            @Override
            public void handle(ActionEvent actionEvent) {
               searchaction();
            }
        });
        submit.setOnAction(new EventHandler<ActionEvent>() {
            @Override
            public void handle(ActionEvent actionEvent) {
                 submitaction(width,height);
            }
        });


    }
    public ObservableList<Item> getInitialData() {
        try (Connection con = DriverManager.getConnection(DBUrl, DBUser, DBPassword);
             Statement stmt = con.createStatement()) {

            // 查询 item_list 表中符合条件的记录
            String query = "SELECT * FROM item_list WHERE name LIKE ? AND is_sold = 0";
            try (PreparedStatement pstmt = con.prepareStatement(query)) {
                pstmt.setString(1, "%" + sw + "%");
                ResultSet rs = pstmt.executeQuery();


                while (rs.next()) {
                    data.add(new Item(rs.getString("name"), rs.getString("price"), rs.getString("seller"),rs.getInt("id")));
                    System.out.println("a");
                    System.out.println(rs.getInt("id"));
                }


                String tagQuery = "SELECT * FROM tag_list WHERE tag_name LIKE ?";
                try (PreparedStatement tagPstmt = con.prepareStatement(tagQuery)) {
                    tagPstmt.setString(1, "%" + sw + "%");
                    ResultSet rsTags = tagPstmt.executeQuery();


                    while (rsTags.next()) {
                        int tagId = rsTags.getInt("id");

                        String relationQuery = "SELECT * FROM tag_item_relation WHERE tag_id = ?";
                        try (PreparedStatement relationPstmt = con.prepareStatement(relationQuery)) {
                            relationPstmt.setInt(1, tagId);
                            ResultSet rsRelations = relationPstmt.executeQuery();


                            while (rsRelations.next()) {
                                int itemId = rsRelations.getInt("Item_id");
                                String itemQuery = "SELECT * FROM item_list WHERE id = ? AND is_sold = 0";
                                try (PreparedStatement itemPstmt = con.prepareStatement(itemQuery)) {
                                    itemPstmt.setInt(1, itemId);
                                    ResultSet rsItem = itemPstmt.executeQuery();


                                    while (rsItem.next()) {
                                        int idf=rsItem.getInt("id");
                                        System.out.println(idf);
                                        if(!data.stream().anyMatch(item -> item.getInfoId()==idf)) {
                                            data.add(new Item(rsItem.getString("name"), rsItem.getString("price"), rsItem.getString("seller"), rsItem.getInt("id")));
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            }

        } catch (SQLException e) {
            System.out.println("暂无该用户数据: " + e.getMessage());
        }
        return data;
    }
    private void setupTableView() {
        TableColumn<Item, String> nameColumn = new TableColumn<>("姓名");
        nameColumn.setCellValueFactory(celldata ->{
            return new SimpleStringProperty(celldata.getValue().getName());
        });


        TableColumn<Item, String> priceColumn = new TableColumn<>("价格");
        priceColumn.setCellValueFactory(celldata ->{
            return new SimpleStringProperty(celldata.getValue().getPrice());
        });

        TableColumn<Item,String> sellerColumn = new TableColumn<>("商家");
        sellerColumn.setCellValueFactory(celldata ->{
            return new SimpleStringProperty(celldata.getValue().getSeller().getName());
        });
        System.out.println("c");
        tableView.getColumns().addAll(nameColumn, priceColumn,sellerColumn);
    }
    private VBox createPage(int pageIndex) {
        int fromIndex = pageIndex * ROWS_PER_PAGE;
        int toIndex = Math.min(fromIndex + ROWS_PER_PAGE, data.size());

        List<Item> pageItems = data.subList(fromIndex, toIndex);
        System.out.println(pageItems.size());
        ObservableList<Item> pageData = FXCollections.observableArrayList(pageItems);
        tableView.setItems(pageData);
        System.out.println("b");
        return new VBox(tableView);
    }
    public void searchaction() {
        data.clear();
        sw = (searchfld.getText()).trim();
        data = getInitialData();

        // 配置TableView
        if (data.isEmpty()) {
            System.out.println("没有找到符合条件的结果");
            pagination.setPageCount(0);  // 如果没有数据，设置分页页数为0
            tableView.setItems(FXCollections.observableArrayList());  // 清空表格数据
            return;
        }

        // 创建分页控件
        int pageCount = (data.size() + ROWS_PER_PAGE - 1) / ROWS_PER_PAGE;  // 计算页数
        pagination.setPageCount(pageCount);
        pagination.setPageFactory(this::createPage);

        // 更新TableView和分页
        tableView.setItems(data); // 直接设置TableView的数据源
        tableView.refresh();  // 强制刷新TableView

        // 设置新的分页内容
        VBox vbox = new VBox(tableView, pagination);
        HBox hb1 = new HBox(searchlb, searchfld, search);
        hb1.setAlignment(Pos.CENTER);
        HBox hb2 = new HBox(submit);
        hb2.setAlignment(Pos.CENTER);

        bp.setCenter(vbox);
        bp.setTop(hb1);
        bp.setBottom(hb2);

        // 刷新界面
  // 显示窗口
    }
    public void submitaction(int width,int height){
        it=tableView.getSelectionModel().getSelectedItem();
        InfoDialog idi=new InfoDialog(by,it,width,height);
    }
    public BorderPane getbp() {
        return bp;
    }

}
